<template>
  <a-modal
    :title="title"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-tabs v-model="tab" forceRender>
        <a-tab-pane key="1" tab="基本信息">
          <a-form-model layout="horizontal" labelAlign="right" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :model="form" :rules="validatorRules">
            <a-form-model-item label="名称" prop="name">
              <a-input placeholder="请输入名称" :disabled="disableSubmit" v-model.trim="form.name"/>
            </a-form-model-item>
            <a-form-model-item label="Excel列号" prop="excelColumn">
              <a-input placeholder="请输入Excel列号" :disabled="disableSubmit" v-model.trim="form.excelColumn"/>
            </a-form-model-item>
            <a-form-model-item label="实体属性" prop="propertyName">
              <a-input placeholder="请输入实体属性" :disabled="disableSubmit" v-model.trim="form.propertyName"/>
            </a-form-model-item>
            <a-form-model-item label="前置解析器" prop="cellPreParserBean">
              <a-select :disabled="disableSubmit" v-model="form.cellPreParserBean" placeholder="请选择解析器">
                <template v-for="(item,i) in parserPreList">
                  <a-select-option :key="i" :value="item.beanId">{{item.parserName}}</a-select-option>
                </template>
              </a-select>
            </a-form-model-item>
            <a-form-model-item  label="前置参数">
              <a-input :disabled="disableSubmit" type="textarea" v-model="form.cellPreParserParam"/>
            </a-form-model-item>
            <a-form-model-item label="后置解析器" prop="cellPostParserBean">
              <a-select :disabled="disableSubmit" v-model="form.cellPostParserBean" placeholder="请选择解析器">
                <template v-for="(item,i) in parserPostList">
                  <a-select-option :key="i" :value="item.beanId">{{item.parserName}}</a-select-option>
                </template>
              </a-select>
            </a-form-model-item>
            <a-form-model-item  label="后置参数">
              <a-input :disabled="disableSubmit" type="textarea" v-model="form.cellPostParserParam"/>
            </a-form-model-item>
            <a-form-model-item label="忽略错误格式数据" :label-col="labelCol2" :wrapper-col="wrapperCol2">
              <a-checkbox :disabled="disableSubmit" v-model.trim="form.ignoreErrorFormatData"></a-checkbox>
            </a-form-model-item>
            <a-form-model-item label="是否处理瞬时属性" :label-col="labelCol2" :wrapper-col="wrapperCol2">
              <a-checkbox :disabled="disableSubmit" v-model.trim="form.saveTransient"></a-checkbox>
            </a-form-model-item>
          </a-form-model>
        </a-tab-pane>
        <a-tab-pane key="2" tab="数据映射" forceRender>
          <vxe-grid
            ref="vxeTable"
            border
            resizable
            keep-source
            :columns="column"
            :data="dataSource"
            :edit-rules="validRules"
            :min-height="200"
            :edit-config="{trigger: 'click', mode: 'row',showStatus: true}"
            :toolbarConfig="{slots: { buttons: 'toolbar_buttons'},perfect: true}"
            @checkbox-change="onSelectChange"
            @checkbox-all="onSelectChange"
          >
            <template v-slot:toolbar_buttons>
              <div class="table-operator">
                <a-button @click="handleAdd" icon="plus" class="theme--perfect-button">添加</a-button>
                <a-button @click="batchDel" type="danger" v-if="selectionRows.length>0" ghost icon="minus"  class="theme--perfect-button">删除</a-button>
              </div>
            </template>
          </vxe-grid>
        </a-tab-pane>
      </a-tabs>

    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { queryParserPreList, queryParserPostList, addMappingRule, editMappingRule } from '@/services/system'

export default {
  name: 'ExcelImportMappingRulesModal',
  props: {
    templateData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: {},
      validatorRules: {
        name: [{ required: true, message: '请输入名称!' }],
        excelColumn: [
          { required: true, message: '请输入Excel列号' }
        ],
        propertyName: [{ required: true, message: '请输入实体属性' }]
      },
      disableSubmit: false,
      parserPostList: [],
      parserPreList: [],
      column: [
        { type: 'checkbox', width: 40 },
        { type: 'seq', width: 40 },
        { title: '关键字', field: 'key', editRender: { name: 'AInput' }},
        { title: '值', field: 'value', editRender: { name: 'AInput' }}
      ],
      dataSource: [],
      validRules: {
        key: [
          { required: true, message: '请输入关键字', trigger: 'change' }
        ],
        value: [
          { required: true, message: '请输入值', trigger: 'change' }
        ]
      },
      selectedRowKeys: [],
      selectionRows: [],
      tab: '1'
    }
  },
  methods: {
    validateDictCode(rule, value, callback) {
      // 重复校验
      var params = {
        tableName: 'sys_dict',
        fieldName: 'dict_code',
        fieldVal: value,
        dataId: this.model.id
      }
      console.log(params)
      callback()
      // duplicateCheck(params).then((res) => {
      //   if (res.success) {
      //     callback()
      //   } else {
      //     callback(res.message)
      //   }
      // })
    },
    add() {
      this.edit({
        entries: []
      })
    },
    edit(record) {
      console.log(record)
      if (record.id) {
        this.visiblekey = true
      } else {
        this.visiblekey = false
      }
      this.model = Object.assign({}, record)
      this.visible = true
      this.dataSource = this.model.entries.length > 0 ? this.model.entries : []
      this.form = pick(this.model, 'id', 'name', 'excelColumn', 'propertyName', 'cellPreParserBean', 'cellPreParserParam', 'cellPostParserBean', 'cellPostParserParam', 'ignoreErrorFormatData')
    },
    // 确定
    async handleOk() {
      // 触发表单验证
      try {
        await this.$refs.ruleForm.validate()
        const tableValidate = await this.$refs.vxeTable.fullValidate()
        if (!tableValidate) {
          const { fullData } = this.$refs.vxeTable.getTableData()
          fullData.forEach(item => { item.mappingRuleId = this.model.id })
          // const templateData = JSON.parse(JSON.stringify(this.templateData))
          if (this.form.id) {
            const data = Object.assign({}, this.model, this.form, { entries: fullData })
            // templateData.mappingRules.forEach((item, i) => {
            //   if (item.id === this.form.id) {
            //     templateData.mappingRules[i] = {
            //       ...data,
            //       entries: fullData
            //     }
            //   }
            // })
            this.updateData(data)
          } else {
            const data = {
              ...this.form,
              entries: fullData,
              importerSolutionId: this.templateData.id
            }
            this.addData(data)
          }
        } else {
          this.tab = '2'
        }
      } catch (err) {
        console.log(err.message, err.warnings)
      }
    },
    updateData(data) {
      editMappingRule(data).then(res => {
        this.resSuccess(res)
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    addData(data) {
      addMappingRule(data).then(res => {
        this.resSuccess(res)
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    resSuccess(res) {
      if (res.success) {
        this.$message.success(res.message)
        this.$emit('ok')
        this.close()
      } else {
        this.$message.warning(res.message)
      }
    },
    // 关闭
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.$refs.ruleForm.resetFields()
      this.visible = false
    },
    getParserPostList() {
      queryParserPostList().then(res => {
        if (res.code === 200) {
          this.parserPostList = res.result
        }
      })
    },
    getParserPreList() {
      queryParserPreList().then(res => {
        if (res.code) {
          this.parserPreList = res.result
        }
      })
    },
    handleAdd() {
      this.$refs.vxeTable.insert()
    },
    batchDel() {
      this.$refs.vxeTable.removeCheckboxRow()
    },
    onSelectChange({ records }) {
      this.selectedRowKeys = []
      records.forEach(item => {
        const rowId = this.$refs.vxeTable.getRowid(item)
        this.selectedRowKeys.push(rowId)
      })
      this.selectionRows = records
    }
  },
  mounted() {
    this.getParserPostList()
    this.getParserPreList()
  }
}
</script>
<style scoped lang="scss">
  .theme--perfect-button{
    border: none;
    background: $vxe-table-header-background-color;
    box-shadow: none;
  }
</style>
